import React, { useState, useRef, useEffect } from 'react'
import { Button, Input, Search } from '@alifd/next'
import { lazy } from 'ice'
import { useMemoizedFn } from 'ahooks'
import ProjectTitleDom from './components/ProjectTitleDom'
import store from '@/store'
import styles from './index.module.scss'

const TreeDom = lazy(() => import('@/components/TreeDom'))

const Project = ({ addBIM, updateBIMName, deleteBIMs, refresh }) => {
  const [graphState, graphDispatchers] = store.useModel('graph')
  const { projectId: _projectId, ugmId: _ugmId, projectData } = graphState

  const [treeType] = useState('project')
  const [projectId, setProjectId] = useState(_projectId)
  const [ugmId, setUgmId] = useState(_ugmId)
  const [initObj] = useState({
    project: {
      installment: {
        building: {
          storey: {}
        }
      },
      ugm: { storey: {} }
    }
  })

  const projectTreeRef = useRef()

  useEffect(() => setUgmId(_ugmId), [_ugmId])

  useEffect(() => setProjectId(_projectId), [_projectId])

  useEffect(() => {
    if (_ugmId && graphState.userType === 'staff') getProject()
    // eslint-disable-next-line no-use-before-define
  }, [_ugmId, graphState.userType, getProject])

  useEffect(() => {
    if (graphState.installmentId && graphState.userType === 'auditor') getProject()
    // eslint-disable-next-line no-use-before-define
  }, [graphState.installmentId, graphState.userType, getProject])

  useEffect(() => {
    if (projectData && projectData.cols && projectData.cols.project.length > 0) {
      const newProjectId = projectData.cols.project[0].id
      if (newProjectId !== _projectId) {
        graphDispatchers.update({ projectId: newProjectId })
      }
    }
  }, [projectData, _projectId, graphDispatchers])

  const getProject = useMemoizedFn(async () => await graphDispatchers.getProject())

  const createKeyTitle = useMemoizedFn(
    ({ name, fatherId, treeKey, idToEye, onlyToEye, setEye, getCheckedKeys, getKeyToId, getIdToKey }) => {
      return (
        <ProjectTitleDom
          name={name}
          idToEye={idToEye}
          onlyToEye={onlyToEye}
          setEye={setEye}
          addBIM={() => addBIM({ type: name, fatherId })}
          deleteBIMs={() => {
            const checkedKeys = getCheckedKeys()
            const keyToId = getKeyToId()
            const idToKey = getIdToKey()
            const ids = checkedKeys
              .map(key => keyToId[key])
              .map(id => projectData.docs[id])
              .filter(
                doc =>
                  !!doc &&
                  doc.definition === name &&
                  idToKey[doc.id].substring(0, idToKey[doc.id].lastIndexOf('-')) === treeKey
              )
              .map(i => i.id)
            deleteBIMs({ ids, type: name, fatherId })
          }}
        />
      )
    }
  )

  const trim = function (str) {
    if (!str) return ''
    return str.replace(/^(\s|\xA0)+|(\s|\xA0)+$/g, '')
  }

  const onSearch = useMemoizedFn(value => {
    projectTreeRef.current.onSearch(value)
  })

  return (
    <div className={styles.Project}>
      <div className={styles.switch}>
        <Input.Group
          addonAfter={
            <Button
              onClick={() => {
                const newProjectId = trim(projectId)
                if (newProjectId !== _projectId) {
                  graphDispatchers.update({ projectId: newProjectId })
                } else if (newProjectId === _projectId) {
                  // getProject()
                }
              }}
            >
              {trim(projectId) !== _projectId ? '载入' : '重载'}
            </Button>
          }
        >
          <Input
            hasClear
            addonTextBefore={'项目名称:'}
            value={projectId}
            defaultValue={projectId}
            onPressEnter={() => {
              const newProjectId = trim(projectId)
              if (newProjectId !== _projectId) {
                graphDispatchers.update({ projectId: newProjectId })
              } else if (newProjectId === _projectId) {
                // getProject()
              }
            }}
            onChange={value => {
              const newValue = trim(value)
              if (newValue !== projectId) setProjectId(newValue)
            }}
          />
        </Input.Group>
      </div>
      <div className={styles.switch}>
        <Input.Group
          addonAfter={
            <Button
              onClick={() => {
                const newUgmId = trim(ugmId)
                if (newUgmId !== _ugmId) {
                  graphDispatchers.update({ ugmId: newUgmId })
                  refresh()
                } else if (newUgmId === _ugmId) {
                  refresh()
                }
              }}
            >
              {trim(ugmId) !== _ugmId ? '载入' : '重载'}
            </Button>
          }
        >
          <Input
            hasClear
            addonTextBefore={'UGM名称:'}
            value={ugmId}
            defaultValue={ugmId}
            onPressEnter={() => {
              const newUgmId = trim(ugmId)
              if (newUgmId !== _ugmId) {
                graphDispatchers.update({ ugmId: newUgmId })
              } else if (newUgmId === _ugmId) {
                refresh()
              }
            }}
            onBlur={() => {
              const newUgmId = trim(ugmId)
              if (newUgmId !== _ugmId) {
                graphDispatchers.update({ ugmId: newUgmId })
              } else if (newUgmId === _ugmId) {
                refresh()
              }
            }}
            onChange={value => {
              const newValue = trim(value)
              if (newValue !== ugmId) setUgmId(newValue)
            }}
          />
        </Input.Group>
      </div>
      <div className={styles.search}>
        <Search
          hasClear
          hasIcon
          shape="simple"
          type="normal"
          placeholder="Search"
          onChange={onSearch}
          fillProps="label"
          dataSource={[
            {
              label: '待处理',
              value: '待处理'
            },

            {
              label: '待审核',
              value: '待审核'
            },
            {
              label: '待识图审核',
              value: '待识图审核'
            },

            {
              label: '审核通过',
              value: '审核通过'
            },
            {
              label: '退回修改',
              value: '退回修改'
            },

            {
              label: '规划失败',
              value: '规划失败'
            },

            {
              label: '已识图',
              value: '已识图'
            },

            {
              label: '待复制规划结果',
              value: '待复制规划结果'
            },

            {
              label: '待户型匹配',
              value: '待户型匹配'
            },

            {
              label: '待上传',
              value: '待上传'
            },

            {
              label: '上传中',
              value: '上传中'
            },

            {
              label: '已上传',
              value: '已上传'
            },

            {
              label: '上传失败',
              value: '上传失败'
            },

            {
              label: '用户驳回修改',
              value: '用户驳回修改'
            },

            {
              label: 'UGM去重失败',
              value: 'UGM去重失败'
            },

            {
              label: '待绑定',
              value: '待绑定'
            }
          ]}
        />
      </div>
      <div className={styles.tree}>
        <div style={{ width: '100%', height: '100%', overflow: 'auto' }}>
          <TreeDom
            ref={projectTreeRef}
            treeType={treeType}
            createKeyTitle={createKeyTitle}
            initObj={initObj}
            updateBIMName={updateBIMName}
          />
        </div>
      </div>
    </div>
  )
}

export default Project
